package com.pucong.gitee.database.backup.business.databaseTask.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pucong.gitee.database.backup.common.entity.database.BackupTask;
import com.pucong.gitee.database.backup.common.selfenum.CommonBoolenEnum;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import com.pucong.gitee.database.backup.configuration.quartz.job.DatabaseTaskQuartz;
import com.pucong.gitee.database.backup.configuration.quartz.MyQuartzScheduler;
import com.pucong.gitee.database.backup.business.databaseTask.mapper.BackupTaskMapper;
import com.pucong.gitee.database.backup.utils.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * 人员表 service实现类
 *
 * @author pucong
 * @url https://gitee.com/pucong
 * @create 2020-06-23
 */
@Service
@Slf4j
public class BackupTaskServiceImpl implements BackupTaskService {

    @Autowired
    private BackupTaskMapper backupTaskMapper;

    @Autowired
    private MyQuartzScheduler myQuartzScheduler;

    @Autowired
    private Scheduler scheduler;

    @Override
    public IPage<BackupTask> getTaskInfoListByPage(int pageNum, int pageSize, BackupTask backupTask) {
        Page<BackupTask> page = new Page<>(pageNum, pageSize);
        //构造分页查询
        LambdaQueryWrapper<BackupTask> params = new LambdaQueryWrapper<>();
        params.eq(StringUtils.isNotBlank(backupTask.getUuid()), BackupTask::getUuid, backupTask.getUuid())
                .eq(StringUtils.isNotBlank(backupTask.getTaskName()), BackupTask::getTaskName, backupTask.getTaskName())
                .eq(StringUtils.isNotBlank(backupTask.getTaskType()), BackupTask::getTaskType, backupTask.getTaskType())
                .eq(backupTask.getProgressStatus() != null, BackupTask::getProgressStatus, backupTask.getProgressStatus());

        params.orderByDesc(BackupTask::getCreateTime);
        IPage<BackupTask> backupTaskIPage = backupTaskMapper.selectPage(page, params);
        return backupTaskIPage;
    }

    @Override
    public int saveTask(String databaseId, BackupTask backupTask) {
        if (StringUtils.isBlank(backupTask.getUuid())) {
            backupTask.setUuid(UUID.uuid());
            backupTask.setCreateTime(new Date());
            backupTaskMapper.insert(backupTask);
        } else {
            backupTask.setCreateTime(null);
            backupTaskMapper.updateById(backupTask);
        }
        if (CommonBoolenEnum.是 == backupTask.getEnabled()) {
            String dataBaseQuartz = null;
            try {
                dataBaseQuartz = myQuartzScheduler.getJobInfo(backupTask.getTaskName(), "dataBaseQuartz");
            } catch (SchedulerException e) {
                log.error("获取定时任务失败", e);
                throw new BusinessException("获取定时任务失败");
            }
            if (StringUtils.isNotBlank(dataBaseQuartz)) {
                // 修改定时任务
                try {
                    myQuartzScheduler.modifyJob(backupTask.getTaskName(), "dataBaseQuartz", getCron(backupTask));
                } catch (SchedulerException e) {
                    log.error("修改定时任务失败", e);
                    throw new BusinessException("修改定时任务失败");
                }
            } else {
                // 添加定时任务
                try {
                    log.error("添加定时任务：" + backupTask.toString());
                    myQuartzScheduler.addTaskJob(backupTask.getTaskName(), "dataBaseQuartz", getCron(backupTask), DatabaseTaskQuartz.class, backupTask.getUuid());
                } catch (SchedulerException e) {
                    log.error("添加定时任务失败", e);
                    throw new BusinessException("添加定时任务失败");
                }
            }
        }
        return 1;
    }

    private String getCron(BackupTask backupTask) {
        String cron = "";
        cron += backupTask.getCronSecond() + "";
        cron += backupTask.getCronMinne() + "";
        cron += backupTask.getCronHour() + "";
        cron += backupTask.getCronDay() + "";
        cron += backupTask.getCronMonth() + "";
        cron += backupTask.getCronYear() + "";
        cron += backupTask.getCronWeek() + "";
        return cron;
    }

    @Override
    public BackupTask getTaskInfoById(String id) {
        return backupTaskMapper.selectById(id);
    }

}
